<!DOCTYPE html>
<html lang="cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>百度地图</title>
  <link rel="stylesheet" type="text/css" href="https://api.map.baidu.com/res/webgl/10/bmap.css" />
  <link href="./font/css/materialdesignicons.min.css" rel="stylesheet">
  <link href="./css/index.css" rel="stylesheet">
  <style>
    #device {
      position: fixed;
      left: 5px;
      bottom: 40px;
      z-index: 100;
    }
  </style>
</head>

<body>
  <select id="device"></select>
  <script src="./js/gcoord.js"></script>
  <script src="./js/lib.js"></script>
  <script src="./js/ha.js"></script>
  <script>
    function readerMarker(initd) {
      ha.readerMarker(({ hass }) => {
        Object.entries(hass.states).forEach(([entityId, state]) => {
          const { latitude, longitude } = state.attributes
          if (latitude && longitude) {
            try {
              const { icon, radius, entity_picture, friendly_name, map } = state.attributes
              // 坐标转换
              const [lng, lat] = ha.transform([longitude, latitude], map === 'gaode' ? gcoord.GCJ02 : gcoord.WGS84, gcoord.BD09)

              // 添加标记
              const domain = entityId.split('.')[0]

              if (domain === 'zone') {
                ha.addIconMarker(lng, lat, { entityId, icon, radius })
                // 初始化居中显示
                if (initd) {
                  ha.centerAndZoom(lng, lat, 12);
                  initd = false
                }
              } else {
                ha.addIconMarker(lng, lat, { entityId, entity_picture, friendly_name })
              }

            } catch (ex) {
              console.error(ex)
            }
          }
        })
      })
    }


    ha.loadMap().then(({ hass }) => {

      // 渲染标记
      readerMarker(true)

      // 菜单
      ha.addContextMenu([{
        text: '编辑地点',
        callback: function () {
          ha.location('/config/zone')
        }
      },
      {
        text: '显示运动轨迹',
        callback: function (point) {
          location.href = `track.html?ak=${ha.ak}&lng=${point.lng}&lat=${point.lat}`
        }
      },
      {
        text: '显示GPS坐标',
        callback: function (point) {
          const [lng, lat] = ha.transform([point.lng, point.lat], gcoord.BD09, gcoord.WGS84)
          parent.alert(`经纬度：${lng}，${lat}`)
        }
      },
      {
        text: '设置我的家到这里',
        callback: function (point) {
          const [lng, lat] = ha.transform([point.lng, point.lat], gcoord.BD09, gcoord.WGS84)
          hass.callService('homeassistant', 'set_location', {
            latitude: lat,
            longitude: lng
          })
          setTimeout(() => {
            readerMarker()
          }, 1000)
        }
      }])

      // 绑定设备
      const select = document.querySelector('#device')
      select.addEventListener('change', () => {
        const entityId = select.value
        const state = hass.states[entityId]
        const { longitude, latitude, map, entity_picture, friendly_name } = state.attributes

        let [lng, lat] = ha.transform([longitude, latitude], map === 'gaode' ? gcoord.GCJ02 : gcoord.WGS84, gcoord.BD09)
        
        ha.centerAndZoom(lng, lat, 18);
      })

      Object.keys(hass.states).filter(ele => ['person', 'device_tracker', 'zone'].includes(ele.split('.')[0])).forEach(entity_id => {
        const { friendly_name, latitude, longitude } = hass.states[entity_id].attributes

        if (latitude && longitude) {
          const option = document.createElement('option')
          option.text = friendly_name
          option.value = entity_id
          select.appendChild(option)
        }
      })

    })
  </script>
</body>

</html>